//
//  FindVC.m
//  u76ho
//
//  Created by m-air-01 on 15/12/25.
//  Copyright © 2015年 LV. All rights reserved.
//

#import "FindVC.h"
#import "RecommendCompanyCell.h"
#import "ChengZhangViewController.h"
#import "ScreenViewController.h"
#import "SearchViewController.h"
#import "LoginViewController.h"

#import "YiQiViewController.h"//公司内容
#import <CoreLocation/CoreLocation.h>


@interface FindVC ()
<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate,UIAlertViewDelegate>

{
    UITableView * _tableView;
    NSMutableArray * dataSource;
    ScreenModel * BanDuanModel;//筛选返回数据模型
    
    NSString * lat ;
    NSString * log;
    
    BOOL  Orshaixuan  ;//是否是筛选返回刷新
    
    NSError *Myerrors;
}
@property (nonatomic,strong) CLLocationManager *locationManager;//定位控件
@property (strong, nonatomic) CCEaseRefresh *refreshView;

@end
static int page = 1;

@implementation FindVC
#pragma mark - 视图生命周期
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];

    

}
-(void)viewWillDisappear:(BOOL)animated
{
    [self.refreshView endRefreshing];
    [super viewWillDisappear:YES];
}
-(void)viewDidLoad
{
    [super viewDidLoad];
    
    Orshaixuan = YES;
    
    self.navigationItem.title = @"发现";
    //定位控件
    self.locationManager = [[CLLocationManager alloc]init];
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter = 0;

    
    
    [self addItems];
    
    
    [self main];
}
-(void)GetLocation{

    if([CLLocationManager locationServicesEnabled]){
        
        _locationManager.delegate = self;

        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8定位需要）
        }
        BOOL enable=[CLLocationManager locationServicesEnabled];
        //是否具有定位权限
        int status=[CLLocationManager authorizationStatus];
        if(enable && (status>=3||status ==kCLAuthorizationStatusNotDetermined)){
            //        [MMProgressHUD showWithTitle:@"locating" status:@""];
          [_locationManager startUpdatingLocation];
            
            //如果没有定位权限
        }else{
            page = 1;
            
            [self requestDatawithLat:@"" lng:@"" withPage:page];
            
            //上拉加载
            _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                [self requestDatawithLat:@"" lng:@"" withPage:++page];
            }];
        
            
             }
        

        
    }

}




// 错误信息
-(void)LocationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    //    [MMProgressHUD dismissWithError:@"locating Error"];
    NSLog(@"error");
}

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
                [_locationManager requestWhenInUseAuthorization];
            break;
            
        default:
            break;
    }
}

// 6.0 以上调用这个函数

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D newCoordinate = newLocation.coordinate;
    NSLog(@"经度：%f,纬度：%f",newCoordinate.longitude,newCoordinate.latitude);
    
    lat = [NSString stringWithFormat:@"%f",newCoordinate.latitude];
    
    log = [NSString stringWithFormat:@"%f",newCoordinate.longitude];
    
    
    
        if (Orshaixuan) {
    
            if (lat&&log) {
                [self requestDatawithLat:lat lng:log withPage:page];
            }else{
    
            [self requestDatawithLat:@"" lng:@"" withPage:page];
    
            }
    
    
        }else{
    
          [self shaixuanrequestDataWithmodel:BanDuanModel andPage:page];
    
            }
    
    
                    //上拉加载
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                        [self requestDatawithLat:lat lng:log withPage:++page];
                    }];
                    
                    
    

    
    
    
    
    // 计算两个坐标距离
    //    float distance = [newLocation distanceFromLocation:oldLocation];
    [manager stopUpdatingLocation];
    manager.delegate =nil;
}

#pragma mark ---  下拉刷新点击
- (void)dropViewDidBeginRefreshing:(CCEaseRefresh *)refreshControl {
    
    
    page = 1;
    
    //刷新重新获取位置
    [self GetLocation];
        
   
    
    

    
}

-(void)main
{
    dataSource = [[NSMutableArray alloc]init];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,-1, self.view.frame.size.width, self.view.frame.size.height-49) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = [UIColor whiteColor];
    
    
    [_tableView registerNib:[UINib nibWithNibName:@"RecommendCompanyCell" bundle:nil] forCellReuseIdentifier:@"RecommendCompanyCell"];
    [self.view addSubview:_tableView];
    
    _tableView.tableFooterView = [UIView new];
    _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    
    self.refreshView = [[CCEaseRefresh alloc] initInScrollView:_tableView];
    [self.refreshView addTarget:self action:@selector(dropViewDidBeginRefreshing:) forControlEvents:UIControlEventValueChanged];
    
    [self.refreshView beginRefreshing];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
}



-(void)requestDatawithLat:(NSString *)lat lng:(NSString *)lng withPage:(int)pageArr
{
    
    //检查网络
    [self reachability];
    
    
    
    
    [U76HONet nearCompanyWithaction:@"" lng:lng lat:lat Page:[NSString stringWithFormat:@"%i",pageArr] pnum:@"15" andDataBlock:^(NSArray *arr) {
        NSLog(@"发现首页获取数据成功了");
        
        
        NSString * string =[NSString stringWithFormat:@"%i",pageArr];
        if ([string isEqualToString:@"1"]) {
            [dataSource removeAllObjects];
            [_tableView.mj_footer resetNoMoreData];

        }
       
        

         if ([_tableView.mj_footer isRefreshing])
        {
            if (arr.count) {
                [_tableView.mj_footer endRefreshing];
            }
            else
            {
                [_tableView.mj_footer endRefreshingWithNoMoreData];
                return ;
            }
        }
        
        [dataSource addObjectsFromArray:arr];
        
        
        [_tableView reloadData];
        
        [self.refreshView endRefreshing];
        
    }];
    
    
}
-(void)shaixuanrequestDataWithmodel:(ScreenModel *)model andPage:(int)pages
{
    [self reachability];
    __weak typeof(self)weakSelf = self;
    
    if (lat &&log) {
        [U76HONet searchResultWithaction:@"" type:model.type keyword:model.keyword industry:model.industry page:[NSString stringWithFormat:@"%i",pages] pnum:model.pnum yqlh:model.yqlh near:model.near lng:log lat:lat andDataBlock:^(NSArray *arr) {
            NSLog(@"筛选获取数据成功列");
            
            
            NSString * string =[NSString stringWithFormat:@"%i",pages];
            if ([string isEqualToString:@"1"]) {
                [dataSource removeAllObjects];
                [_tableView.mj_footer resetNoMoreData];
                
            }
            if ([_tableView.mj_footer isRefreshing])
            {
                if (arr.count) {
                    [_tableView.mj_footer endRefreshing];
                }
                else
                {
                    [_tableView.mj_footer endRefreshingWithNoMoreData];
                    return ;
                }
            }
            
            
            
            [dataSource addObjectsFromArray:arr];
            [_tableView reloadData];
            
            [weakSelf.refreshView endRefreshing];
            
        }];
    }else{
    
    
        [U76HONet searchResultWithaction:@"" type:model.type keyword:model.keyword industry:model.industry page:[NSString stringWithFormat:@"%i",pages] pnum:model.pnum yqlh:model.yqlh near:model.near lng:@"" lat:@"" andDataBlock:^(NSArray *arr) {
            NSLog(@"筛选获取数据成功列");
            
            
            NSString * string =[NSString stringWithFormat:@"%i",pages];
            if ([string isEqualToString:@"1"]) {
                [dataSource removeAllObjects];
                [_tableView.mj_footer resetNoMoreData];
                
            }
            if ([_tableView.mj_footer isRefreshing])
            {
                if (arr.count) {
                    [_tableView.mj_footer endRefreshing];
                }
                else
                {
                    [_tableView.mj_footer endRefreshingWithNoMoreData];
                    return ;
                }
            }
            
            
            
            [dataSource addObjectsFromArray:arr];
            [_tableView reloadData];
            
            [weakSelf.refreshView endRefreshing];
            
        }];

    
    
    }
    
    
    }
- (void)reachability
{
    // 检测网络连接状态
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 连接状态回调处理
    /* AFNetworking的Block内使用self须改为weakSelf, 避免循环强引用, 无法释放 */
    //    __weak typeof(self) weakSelf = self;
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
     {
         switch (status)
         {
             case AFNetworkReachabilityStatusUnknown:
                 // 回调处理
                 break;
             case AFNetworkReachabilityStatusNotReachable:
//                 [Singleton alerSendMessage:@""];
                 
                 [self.refreshView endRefreshing];

                 if ([_tableView.mj_header isRefreshing]) {
                     [_tableView.mj_header endRefreshing];
                 }
                 if ([_tableView.mj_footer isRefreshing])
                 {
                     [_tableView.mj_footer endRefreshing];
                 }
                 // 回调处理
                 break;
             case AFNetworkReachabilityStatusReachableViaWWAN:
                 // 回调处理
                 break;
             case AFNetworkReachabilityStatusReachableViaWiFi:
                 // 回调处理
                 break;
             default:
                 break;
         }
     }];
}

#pragma mark - _tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecommendCompanyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendCompanyCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (dataSource.count!=0) {
        cell.scompaymodel = dataSource[indexPath.row];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        if ([self isLogin]) {
            YiQiViewController * companyVC = [[YiQiViewController alloc]init];
            
            
            SCompanyModel * model = dataSource[indexPath.row];
            
            companyVC.headerString = model.ico;
            
            companyVC.yqCode = model.code;
            companyVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController  pushViewController:companyVC animated:YES];
           // companyVC.hidesBottomBarWhenPushed = NO;
        }
    
    
    
//    if ([self isLogin]) {
//        CompanyViewController * companyVC = [[CompanyViewController alloc]init];
//        SCompanyModel * model = dataSource[indexPath.row];
//        companyVC.yqCode = model.code;
//        
//       // companyVC.MyTitle = model.companyname;
//        companyVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController  pushViewController:companyVC animated:YES];
//       // companyVC.hidesBottomBarWhenPushed = NO;
//    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}
-(BOOL)isLogin
{
    
    
    if ([Singleton share].code) {
        NSLog(@"登录了");
        return YES;
        
    }
    else
    {
        //        NSLog(@"还没登录呢");
        //        LoginViewController * loginVC = [[LoginViewController alloc]init];
        //        [self.navigationController pushViewController:loginVC animated:NO];
        //        return NO;
        if (SYSTEM_VERSION >= 8.0) {
            UIAlertController * alerVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录是否登录" preferredStyle:UIAlertControllerStyleAlert];
            
            [self showDetailViewController:alerVC sender:nil];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                LoginViewController * loginVC = [[LoginViewController alloc]init];
                
                UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
                nav.navigationBarHidden = YES;
                
                //[self.navigationController pushViewController:nav animated:YES];
                [self presentViewController:nav animated:YES completion:nil];
                
                

                
            }]];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }]];
            
            
        }
        else
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有登录是否登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
        return NO;
        
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = (int)buttonIndex;
    if (i == 0) {
        
    }
    else if(i == 1)
    {
        LoginViewController * loginVC = [[LoginViewController alloc]init];
        
        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        nav.navigationBarHidden = YES;
        
        //[self.navigationController pushViewController:nav animated:YES];
        [self presentViewController:nav animated:YES completion:nil];
       
    }
}

#pragma mark - AddItems
-(void)addItems
{
    UIButton * searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0, 0, 19, 18);
//    [searchBtn setImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
    [searchBtn setBackgroundImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc]initWithCustomView:searchBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton * shaiXuanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shaiXuanBtn.frame = CGRectMake(0,0, 30, 50);
//    [shaiXuanBtn setTitle:@"筛选" forState:UIControlStateNormal];
    [shaiXuanBtn setImage:[UIImage imageNamed:@"筛选"] forState:UIControlStateNormal];
    [shaiXuanBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [shaiXuanBtn addTarget:self action:@selector(shaiXuanBtnActionbig:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:shaiXuanBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

#pragma mark ---筛选
-(void)shaiXuanBtnActionbig:(UIButton *)btn
{
    ScreenViewController * screenVC = [[ScreenViewController alloc]init];
    __weak typeof(self)weakSelf = self;
    page = 1;
    [screenVC setScreenmodelBlock:^(ScreenModel * model) {
        
        [weakSelf shaixuanrequestDataWithmodel:model andPage:page];
         BanDuanModel = model;
        
        Orshaixuan = NO;
        

        //上拉加载
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [weakSelf shaixuanrequestDataWithmodel:model andPage:++page];
        }];

        NSLog(@"开始筛选了");
    }];
    screenVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:screenVC animated:YES];
    //screenVC.hidesBottomBarWhenPushed = NO;
}
#pragma  mark --搜索
-(void)searchBtnAction:(UIButton *)btn
{
    SearchViewController * searchVC = [[SearchViewController alloc]init];
    searchVC.navigationItem.hidesBackButton = YES;
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
    //searchVC.hidesBottomBarWhenPushed = NO;
}


@end
